package com.proton.carepatchtemp.activity;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.Profile;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.ImageUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.PrfCenter;
import com.proton.carepatchtemp.utils.net.oss.OSSUtils;
import com.sdsmdg.tastytoast.TastyToast;
import com.sinping.iosdialog.dialog.widget.ActionSheetDialog;

import java.io.File;
import java.util.Calendar;

import cn.qqtheme.framework.picker.DatePicker;

public class ProfileEditActivity extends BaseActivity {
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 4;
    protected Uri tempUri;
    private Profile mProfile;
    private String ossAvatorUri = "";
    private DatePicker mDatePicker;
    private ProgressDialog mProgressDialog;
    private ImageButton mBtnBack;
    /**
     * 档案编辑
     */
    private TextView mTvAddProfileTitle;
    private SimpleDraweeView mSdvProfileAvatar;
    private LinearLayout mLnlProfileAvatar;
    /**
     * 姓名
     */
    private TextView mTvRealName;
    /**
     * 性别
     */
    private TextView mTvSex;
    private LinearLayout mLnlProfileSex;
    /**
     * 1996-3-4
     */
    private TextView mTvProfileBirthday;
    private LinearLayout mLnlProfileBirthday;
    /**
     * ANDJKGNADNGID
     */
    private TextView mTvProfileCode;
    private LinearLayout mLnlProfileCode;
    private LinearLayout mLnlParentProfileEdit;
    private LinearLayout mLnlProfileName;
    private TextView mTvProfileWechatIntro;
    private File mCameraFile = new File(FileUtils.getDataCache(), "image.jpg");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_edit);
        initView();
        //  出生年月选择器
        mDatePicker = new DatePicker(this, DatePicker.YEAR_MONTH_DAY);
        mDatePicker.setLabel(getString(R.string.string_year), getString(R.string.string_month), getString(R.string.string_day));
        mDatePicker.setRangeStart(1900, 1, 1);//开始范围
        mDatePicker.setRangeEnd(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH) + 1, Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + 1);//结束范围
        mDatePicker.setSelectedItem(2000, 1, 1);
        mDatePicker.setTitleText(R.string.birthday);

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        setListener();

        if (null != getIntent().getExtras()) {
            mTvAddProfileTitle.setText(R.string.edit_profile);
            mProfile = (Profile) getIntent().getExtras().get(Extras.PRF_EDIT);

            if (mProfile == null) return;
            ossAvatorUri = mProfile.getAvatar();
            mSdvProfileAvatar.setImageURI(mProfile.getAvatar());

            if (!TextUtils.isEmpty(mProfile.getBirthday())) {
                String[] s = mProfile.getBirthday().split("-");
                StringBuilder str = new StringBuilder();
                str.append(s[0]).append("-").append(s[1]).append("-").append(s[2]);
                mTvProfileBirthday.setText(str);
            }


            if (1 == mProfile.getGender()) {
                mTvSex.setText(R.string.male);
            } else {
                mTvSex.setText(R.string.female);
            }
            mTvRealName.setText(mProfile.getRealname());
        } else {
            mProfile = new Profile();
        }

        if (SpUtils.getBoolean(Extras.APP_EDITION, false)) {
            mTvProfileCode.setVisibility(View.GONE);
            mTvProfileWechatIntro.setVisibility(View.GONE);
        } else {
            mTvProfileCode.setText(PrfCenter.obtainProfileID(mProfile));
        }

    }

    @Override
    public void dealEvent(MainEvent event) {

    }

    private void initView() {
        mBtnBack = findViewById(R.id.btn_back);
        mTvAddProfileTitle = findViewById(R.id.tv_add_profile_title);
        mSdvProfileAvatar = findViewById(R.id.sdv_profile_avatar);
        mLnlProfileAvatar = findViewById(R.id.lnl_profile_avatar);
        mTvRealName = findViewById(R.id.tv_real_name);
        mTvSex = findViewById(R.id.tv_sex);
        mLnlProfileSex = findViewById(R.id.lnl_profile_sex);
        mTvProfileBirthday = findViewById(R.id.tv_profile_birthday);
        mLnlProfileBirthday = findViewById(R.id.lnl_profile_birthday);
        mTvProfileCode = findViewById(R.id.tv_profile_code);
        mLnlProfileCode = findViewById(R.id.lnl_profile_code);
        mLnlParentProfileEdit = findViewById(R.id.lnl_parent_profile_edit);
        mLnlProfileName = findViewById(R.id.lnl_profile_name);
        mTvProfileWechatIntro = findViewById(R.id.tv_profile_wechat_intro);

        if (VCare.isInternal) {
            mTvProfileWechatIntro.setVisibility(View.GONE);
            mLnlProfileCode.setVisibility(View.GONE);
        }
    }

    @Override
    protected void setListener() {
        mBtnBack.setOnClickListener(view -> {
            finish();
        });

        mLnlProfileName.setOnClickListener(v -> {
            final EditText inputServer = new EditText(this);
            inputServer.setMaxLines(1);
            inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.string_real_name)).setIcon(android.R.drawable.ic_menu_edit).setView(inputServer)
                    .setNegativeButton(getString(R.string.string_cancel), null);
            builder.setPositiveButton(getString(R.string.string_confirm), (dialog, which) -> {
                mTvRealName.setText(inputServer.getText());
                mProfile.setRealname(inputServer.getText().toString().trim());
                mProfile.setTitle(inputServer.getText().toString().trim());
                PrfCenter.edit(mProfile);
            });
            builder.show();
        });

        mLnlProfileAvatar.setOnClickListener(v -> {
            if (NetUtils.noNet()) {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                return;
            }
            showChoosePicDialog();
        });

        mLnlProfileSex.setOnClickListener(v -> {
            chooseSex();
        });

        mLnlProfileBirthday.setOnClickListener(v -> {
            mDatePicker.show();
        });

        mLnlProfileCode.setOnClickListener(v -> {
            onClickCopy(mTvProfileCode);
        });

        mDatePicker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year, month, day) -> {
            mTvProfileBirthday.setText(year + "-" + month + "-" + day);
            mProfile.setBirthday(mTvProfileBirthday.getText().toString().trim());
            PrfCenter.edit(mProfile);
        });
    }

    @Override
    public void onEventMainThread(MainEvent event) {

    }

    public void onClickCopy(TextView v) {
        final String[] stringItems = {getString(R.string.string_copy)};
        final ActionSheetDialog dialog = new ActionSheetDialog(ProfileEditActivity.this, stringItems, mLnlParentProfileEdit);
        dialog.title(getString(R.string.string_copy_profile_id));
        dialog.titleTextSize_SP(14F);
        dialog.show();
        dialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (position) {
                case 0:
                    // 从API11开始android推荐使用android.content.ClipboardManager
                    // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
                    ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    cm.setPrimaryClip(ClipData.newPlainText(null, v.getText()));
                    TastyUtils.makeTextShort(R.string.string_copy_success, TastyToast.SUCCESS);
                    break;
                default:
                    break;
            }
            dialog.dismiss();
        });
    }

    private void chooseSex() {
        final String[] stringItems = {getString(R.string.string_male), getString(R.string.string_female)};
        final ActionSheetDialog dialog = new ActionSheetDialog(ProfileEditActivity.this, stringItems, mLnlParentProfileEdit);
        dialog.title(getString(R.string.string_choose_sex));
        dialog.titleTextSize_SP(14F);
        dialog.show();
        dialog.setOnOperItemClickL((parent, view1, position, id) -> {
            switch (position) {
                case 0:
                    mTvSex.setText(getString(R.string.string_male));
                    mProfile.setGender(1);
                    PrfCenter.edit(mProfile);
                    break;
                case 1:
                    mTvSex.setText(getString(R.string.string_female));
                    mProfile.setGender(2);
                    PrfCenter.edit(mProfile);
                    break;
                default:
                    break;
            }
            dialog.dismiss();
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }


    /**
     * 显示修改头像的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.string_set_avatar));
        String[] items = {getString(R.string.string_select_photo), getString(R.string.string_take_photo)};
        builder.setNegativeButton(getString(R.string.string_cancel), null);
        builder.setItems(items, (dialog, which) -> {
            switch (which) {
                case CHOOSE_PICTURE: // 选择本地照片
                    openGallery();
                    break;
                case TAKE_PICTURE: // 拍照
                    openCamera();
                    break;
            }
        });
        builder.create().show();
    }

    private void openGallery() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    }

    private void openCamera() {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tempUri = FileProvider.getUriForFile(
                    this,
                    getPackageName() + ".FileProvider",
                    mCameraFile);
        } else {
            tempUri = Uri.fromFile(mCameraFile);
        }
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(takePhotoIntent, TAKE_PICTURE);
    }

    /**
     * 裁剪图片方法实现
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    /**
     * 保存裁剪之后的图片数据
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            uploadPic(photo);
        }
    }

    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        // 注意这里得到的图片已经是圆形图片了
        // bitmap是没有做个圆形处理的，但已经被裁剪了

        String imagePath = ImageUtils.savePhoto(bitmap, FileUtils.avatar);
        Log.e("imagePath", imagePath + "");
        if (imagePath != null) {
            // 拿着imagePath上传了
            // ...
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    mProgressDialog.setMessage(getString(R.string.string_uploading));
                    mProgressDialog.show();
                }

                @Override
                protected Void doInBackground(Void... params) {
                    ossAvatorUri = OSSUtils.uploadImg(imagePath);
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {

//                    Uri uri = Uri.parse(ossAvatorUri.toString());
                    mSdvProfileAvatar.setImageURI(ossAvatorUri);
                    mProfile.setAvatar(ossAvatorUri);
                    PrfCenter.edit(mProfile);
                    mProgressDialog.dismiss();
                    super.onPostExecute(aVoid);
                }
            }.execute();

        }
    }
}
